<template>
  <!-- 内容区域 -->
  <div class="add_site">
    <el-tabs
      class="tabHight"
      :tab-position="tabPosition"
      v-model="siteTabs"
      @tab-click="invalidateMap"
    >
      <el-tab-pane label="详情" name="first">
        <!-- from表单 -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="auto"
          size="mini"
          class="tabHight_auto"
        >
          <el-form-item label="Token:" prop="token">
            <el-input
              v-model="ruleForm.token"
              placeholder="请输入2-30字符标识符"
            ></el-input>
          </el-form-item>
          <el-form-item label="名称:" prop="sitename">
            <el-input
              v-model="ruleForm.sitename"
              placeholder="请输入15字符以内名称"
            ></el-input>
          </el-form-item>
          <!-- 站点类型 -->
          <el-form-item label="站点类型:" prop="sitetoken">
            <el-select
              class="w100"
              v-model="ruleForm.sitetoken"
              placeholder="请选择站点类型"
            >
              <el-option
                v-for="item in areaTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.token"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="图像:" prop="imageUrl">
            <div style="width: 100%">
              <el-row>
                <el-col :span="6">
                  <app-upload
                    tips=""
                    :is-resolution="true"
                    :width="720"
                    :height="294"
                    @subUploadSucceed="handleUploadSucceed"
                  />
                </el-col>
                <el-col :span="18">
                  <div class="imageHome" v-if="showImg">
                    <img
                      v-if="ruleForm.imageUrl"
                      :src="ruleForm.imageUrl | filtersFileUrl()"
                      class="image-size"
                    />
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
          <el-form-item label="描述:" prop="description">
            <el-input
              type="textarea"
              v-model="ruleForm.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- 涵盖样式 -->
      <el-tab-pane label="边界" name="second">
        <div id="map"></div>
      </el-tab-pane>
      <!-- 元数据样式 -->
      <el-tab-pane label="元数据" name="third">
        <metaData
          :editmetaData="editmetaData"
          :isedit="isedit"
          @sendmetaDatas="sendmetaData"
        />
      </el-tab-pane>
    </el-tabs>
    <el-divider style="color: #000000"></el-divider>
    <div class="dialog-footer">
      <el-button @click="dialogFormVisible" size="mini">取 消</el-button>
      <el-button
        type="primary"
        @click="submitForm('ruleForm')"
        size="mini"
        :loading="btnLoading"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import CoverDatatab from "../opensite/coverDatatab.vue";
import MetaData from "../opensite/metaData.vue";
import AppUpload from "../device/devicegroups/UploadImage.vue";
import "../../styles/uploadImg.sass";
import {
  initMap,
  addControlOptions,
  createIcon,
} from "../../utils/leaflet-map";
import { addAreas, getAreatypes } from "@/api/superlinkAreat";
import { TOKEN_RULES } from "@/utils/local";
export default {
  components: {
    CoverDatatab,
    MetaData,
    AppUpload,
  },
  data() {
    return {
      btnLoading: false,
      tabPosition: "left",
      map: "",
      layer: "",
      isedit: false, //true为编辑页进入，false为添加页进入
      siteTabs: "first",
      value: "",
      ruleForm: {
        token: "",
        sitename: "",
        imageUrl: "",
        description: "",
        sitetoken: "",
        latlngMap: {},
        bounds: {},
      },
      areaTypeList: [],
      typename: "",
      coverData: [],
      metaData: {},
      editcoverData: [],
      editmetaData: [],
      formInline: { date: "", name: "" },
      rules: {
        token: TOKEN_RULES,
        sitename: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 15, message: "输入格式不正确", trigger: "blur" },
        ],
        imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
        sitetoken: [
          {
            required: true,
            message: "请选择站点类型",
            trigger: ["blur", "change"],
          },
        ],
      },
      // coverDataSelectedIds: [],
      metaDataJson: {},
      createArea: {},
      typetokn: "",
      mapBounds: [],
    };
  },
  mounted() {
    this.AreaTypes();
    this.load_Map_2();
  },
  computed: {
    showImg: function () {
      return this.ruleForm.imageUrl != "";
    },
  },
  methods: {
    // 图片上传
    handleUploadSucceed(url) {
      this.ruleForm.imageUrl = url;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    // 请求站点类型列表
    AreaTypes() {
      var that = this;
      var param = { includeContainedAreaTypes: false, page: 1, pageSize: 100 };
      getAreatypes(param).then((res) => {
        that.areaTypeList = res.data.results;
      });
    },
    // 点击下拉
    selectAreaTypes(val) {
      console.log(val); // 此时打印的直接就是id
    },

    dialogFormVisible() {
      var that = this;
      this.$emit("closaddsite", false);
      this.ruleForm = {
        token: "",
        sitename: "",
        imageUrl: "",
        description: "",
        sitetoken: "",
        bounds: {},
      };
      that.map.remove(),
        (this.layer = ""),
        (this.formInline = { date: "", name: "" });
      this.metaData = [];
    },

    // 初始化地图
    load_Map_2() {
      var that = this;
      var latlng = that.ruleForm.bounds;
      var map = initMap("map", latlng, 5);
      addControlOptions(map, [
        "drawRectangle",
        "drawPolygon",
        "removalMode",
        "enable",
        "editMode",
      ]);

      map.on("pm:create", (e) => {
        if (that.layer) {
          map.removeLayer(that.layer); // 移除已有图层,限制只有一个marker
        }
        // 清空参数，只保留当前
        that.mapBounds = [];
        // 转换数据格式
        that.layer = e.layer;
        let maplist = e.layer._latlngs;
        let ele = {};
        maplist[0].forEach((item) => {
          ele = {
            latitude: item.lat,
            longitude: item.lng,
          };
          that.mapBounds.push(ele);
        });

        // 添加区域完成后，可编辑
        that.layer.on("pm:edit", (e) => {
          that.mapBounds = [];
          let mapeditlist = that.layer._latlngs;
          let ele = {};
          mapeditlist[0].forEach((item) => {
            ele = {
              latitude: item.lat,
              longitude: item.lng,
            };
            that.mapBounds.push(ele);
          });
        });
      });

      map.on("pm:remove", (e) => {
        that.layer = [];
      });
      that.map = map;
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.areaTypeToken = this.ruleForm.sitetoken;
          formData.name = this.ruleForm.sitename;
          formData.metadata = this.metaDataJson;
          formData.imageUrl = this.ruleForm.imageUrl;
          formData.description = this.ruleForm.description;
          formData.token = this.ruleForm.token;
          formData.backgroundColor = "";
          formData.borderColor = "";
          formData.foregroundColor = "";
          formData.icon = "";
          formData.bounds = this.mapBounds;
          this.btnLoading = true;
          addAreas(formData)
            .then((res) => {
              const { data } = res;
              this.createArea = data;
              this.$msg({
                type: "success",
                message: "操作成功!",
              });
              this.dialogFormVisible();
              this.$emit("submitadd", false);
            })
            .finally((f) => {
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },

    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "second") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    },
  },
};
</script>

<style scoped lang='scss'>
/deep/.el-button--primary {
  /* background-color: #2680d2; */
  /* border-color: #2680d2; */
}

/deep/ .el-main {
  padding: 20px;
}
.el-row {
  margin-top: 0px;
}
/deep/ .el-card__body {
  padding: 0;
}
.el-card {
  margin-top: 12px;
  height: 185px;
  background-image: url("http://img-u-3.51miz.com/preview/element/00/01/11/37/E-1113756-4765F0FC.jpg!/quality/90/unsharp/true/compress/true/format/jpg/fh/320");
}
.el-card:hover {
  /* 鼠标变小手 */
  cursor: pointer;
}
.demo-form-inline {
  margin-top: 10px;
}
.avatar {
  text-align: center;
  margin-top: 12px;
}
.name {
  margin-top: 13px;
  text-align: center;
  font-weight: 700;
  font-size: 18px;
}
.text {
  font-size: 14px;
  margin-top: 11px;
  text-align: center;
}
.element-icons {
  font-size: 20px;
  font-weight: 600;
  float: left;
  margin-top: -91px;
  margin-left: 91%;
}
.el-pagination {
  margin-left: 32%;
  margin-top: 30px;
}

.list-content {
  margin-top: -25px;
}
.dialog-footer {
  /* width: 100%; */
  /* float: right; */
  /* margin-top: 15px; */
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.title-text {
  color: #ffffff;
}

.span-box {
  display: inline-block;
  position: relative;
}
.ico-pre {
  position: absolute;
  left: -21px;
  top: 12px;
}
#map {
  width: 100%;
  height: calc(50vh);
  z-index: 1;
}
</style>>
